package com.example.springBoot.common;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;


import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

@Controller
public class FileUploadController {

	@RequestMapping("/fileUpload")
	@ResponseBody
	public ReturnJson fileupload(MultipartFile file) {
		if (file.isEmpty()) {
			return new ReturnJson(false, "上传文件不能为空");
		}
		// 获取上传文件名称
		String tmpfileName = file.getOriginalFilename();
		// 获取图片的扩展名
		String extensionName = StringUtils.substringAfter(tmpfileName, ".");
		// 新的图片文件名 = 获取时间戳+"."图片扩展名
		String fileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName;
		String[] extarr = new String[] { "jpeg", "png", "jpg" };

		if (!Arrays.asList(extarr).contains(extensionName)) {
			return new ReturnJson(false, "文件上传类型不正确");
		}
		String path = this.getClass().getResource("/").getPath() + "/uploadFile";
		File dest = new File(path + "/" + fileName);
		if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
			dest.getParentFile().mkdir();
		}
		try {
			file.transferTo(dest); // 保存文件
			return new ReturnJson(true, fileName);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ReturnJson(true, "文件上传失败");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ReturnJson(true, "文件上传失败");
		}
	}

	@RequestMapping("/getfilebyname")
	@ResponseBody
	public Resource getfilebypath(String filename) {
		String path = this.getClass().getResource("/").getPath() + "/uploadFile";
		Resource resource = new FileSystemResource(path + "/" + filename);
		if (resource.exists()) {
			return resource;
		} else {
			String pathdefault = this.getClass().getResource("/").getPath() + "/static/images";
			Resource resourcedefault = new FileSystemResource(pathdefault + "/defualt.jpg");
			return resourcedefault;
		}
	}
	
	@RequestMapping("/gettest")
	@ResponseBody
	public String gettest(){
		String path = this.getClass().getResource("/").getPath();
		return path;
	}
}
